import { createRouter, createWebHashHistory } from "vue-router";
import HomeView from "@/views/home.vue";
import { useRoutesStore } from "@/stores/counter";
let Module = import.meta.glob("@/views/**/*.vue");

//基本的路由规则，不需要登录就能访问
export const initRoutes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path:"/test",
    component:()=>import("@/views/test.vue")
  },
  {
    path: "/home",
    name: "home",
    component: HomeView,
  },
  {
    path: "/about",
    name: "about",
    component: () => import("@/views/About.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/Login.vue"),
  },
  {
    path:"/:pathMatch(.*)*",
    component:()=>import("@/views/404.vue")
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes: initRoutes,
});

//下面这里会导致一个问题，就是刷新的时候页面时无效的！！！！
router.beforeEach((to, from, next) => {
  // console.log(to, from);
  var path = localStorage.getItem('new')
 
  const store = useRoutesStore();
  // console.log(store.routes);
  let routes = store.routes;
  routes.forEach((item) => {
    // 还是需要将这里的item进行修改才行！！！
    let route = Object.assign({}, item);
    let str = item.component;
    // route.component = Module[`/src/views/${str}.vue`];
    // console.log(Module);
    route.component = ()=>import(`/src/views/${str}.vue`)
    // console.log(Module[`/src/views/${str}.vue`](),import(`/src/views/${str}.vue`));
    // console.log(route);
    router.addRoute(route); // 动态添加可访问路由表
  }); //需要本地持久化！！！！
  // console.log(router.getRoutes());
  if(path==to.path){//如果是刷新，就进行下面的操作！！！
    localStorage.removeItem('new')
    router.replace({...to});
  }
  next();
});


//存访问路由
router.afterEach((to, from) => {
  localStorage.setItem("new",to.path)
  })

export default router;
